package com.example.demo.controller;

import com.example.demo.config.getCurrentTime;
import com.example.demo.model.service.MarkService;
import com.example.demo.model.service.OperateRecordService;
import com.example.demo.model.valueObject.Mark;
import com.example.demo.model.valueObject.OperateRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;

@Controller
public class MarkOperate {
    private final static String addMarkUrl = "/admin/addMark";
    private final static String reduceMarkUrl = "/admin/reduceMark";
    private final static String OneUsersMarksUrl = "redirect:/admin/OneUsersMarks";
    @Autowired
    private MarkService markService;
    @Autowired
    private OperateRecordService operateRecordService;
    @PostMapping(addMarkUrl+"/{id}")
    public String addMark(HttpServletRequest request, @PathVariable String id, @RequestParam("mark")String mark)
    {
        if(mark.trim().equals(""))
        {
            return OneUsersMarksUrl;
        }
        markService.addMarkToAUser(id,Integer.parseInt(mark.trim()));
        OperateRecord operateRecord = new OperateRecord();
        operateRecord.setUserId(id);
        operateRecord.setOperateTime(getCurrentTime.getTime());
        operateRecord.setOperate("+"+mark);
        operateRecordService.insertAnOperateRecord(operateRecord);
        return OneUsersMarksUrl+"/"+id;
    }
    @PostMapping(reduceMarkUrl+"/{id}")
    public String reduceMark(HttpServletRequest request, @PathVariable String id, @RequestParam("mark")String mark
            ,@RequestParam("oldMark")String oldMark)
    {
        if(mark.trim().equals(""))
        {
            return OneUsersMarksUrl;
        }
        //扣除的大于原来的积分
        if(Integer.parseInt(mark)>Integer.parseInt(oldMark))
        {
            String message = "error";
            return OneUsersMarksUrl+"/"+id+"/"+message;
        }
        markService.reduceMarkToAUser(id,Integer.parseInt(mark.trim()));
        OperateRecord operateRecord = new OperateRecord();
        operateRecord.setUserId(id);
        operateRecord.setOperateTime(getCurrentTime.getTime());
        operateRecord.setOperate("-"+mark);
        operateRecordService.insertAnOperateRecord(operateRecord);
        return OneUsersMarksUrl+"/"+id;
    }
}
